import { Extension } from '@tiptap/core';
import { getDeviceDPI } from '../../utils/index.js'
const FirstIndent = Extension.create({
  name: 'firstIndent',
  addOptions() {
    return {
      types: ['paragraph'],
    };
  },
  addGlobalAttributes() {
    return [
      {
        types: this.options.types,
        attributes: {
          // 实际缩进
          textIndent: {
            default: null,
            parseHTML: element => {
              return element.style.textIndent || null
            },
            renderHTML: attributes => {
              return attributes.textIndent ? { style: `text-indent: ${attributes.textIndent}` } : {};
            }
          },
          // 记录当前缩进登记
          dataIndent: {
            default: 0,
            renderHTML: attributes => {
              return attributes.dataIndent ? { 'data-indent': `${attributes.dataIndent}` } : {};
            }
          }
        },
      },
    ];
  },
  addCommands() {
    return {
      /**
       * 设置首行缩进
       * @param {"in" | "out"} type
       * @returns {function(*): *}
       */
      setFirstIndent: (type) => (arg) => {
        const { state, dispatch } = arg
        const { selection } = state
        const { from, to } = selection
        const tr = state.tr
        state.doc.nodesBetween(from, to, (node, pos) => {
          if (node.isBlock) {
            const firstChild = node.content?.firstChild
            let firstChildFontSizeNum = 12 // 大小
            let firstChildFontSizeUnit = 'px' // 单位
            let currentIndent = node.attrs.dataIndent || 0

            // 计算当前段落首个文本节点的字体大小
            if (firstChild) {
              for (const mark of firstChild?.marks || []) {
                if (mark.type.name === 'textStyle') {
                  firstChildFontSizeNum = mark.attrs.fontSize.match(/^\d+/)[0]
                  firstChildFontSizeUnit = mark.attrs.fontSize.slice(firstChildFontSizeNum.length)
                }
              }
              let textIndentNum
              let textIndentUnit
              // 计算当前选中段落的缩进值
              if (node.attrs.textIndent) {
                textIndentNum = node.attrs.textIndent?.match(/^\d+/)?.[0]
                textIndentUnit = node.attrs.textIndent?.slice(textIndentNum.length)
              }
              if (firstChildFontSizeUnit && textIndentUnit) {
                if (firstChildFontSizeUnit !== textIndentUnit) {
                  const dpi = getDeviceDPI()
                  if (firstChildFontSizeUnit === 'pt') {
                    textIndentNum = textIndentNum * dpi / 72
                    currentIndent = Math.floor(textIndentNum / firstChildFontSizeNum)
                  }
                }
              }
            }
            if (type === 'in') {
              currentIndent+=2
            } else {
              currentIndent-=2
              if (currentIndent < 0) {
                currentIndent = 0
              }
            }
            tr.setNodeMarkup(pos, null, {
              ...node.attrs,
              textIndent: currentIndent * firstChildFontSizeNum + firstChildFontSizeUnit,
              dataIndent: currentIndent
            })
          }
        })

        if (tr.docChanged) {
          dispatch && dispatch(tr)
          return true
        }
        return false
        // return this.options.types.every(type => commands.updateAttributes(type, { textIndent: alignment === 'in' ? ++this.options.IndentLevel : --this.options.IndentLevel }));
      },
      unsetFirstIndent: () => ({ commands }) => {
        this.options.IndentLevel = 0
        return this.options.types.every(type => {
          commands.resetAttributes(type, ['textIndent','dataIndent'])
        });
      },
    };
  },
  addKeyboardShortcuts() {
    return {
      Tab: () => this.editor.commands.setFirstIndent('in'),
      'Shift-Tab': () => this.editor.commands.setFirstIndent('out')
    };
  },
});

export { FirstIndent, FirstIndent as default }
